﻿using DatabaseHelper;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace IJZ.SQLServer.StoredProcedureHelper
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        private DataSet SchemaData;

        public MainWindow()
        {
            InitializeComponent();
            txtConnection.Text = ConfigurationManager.ConnectionStrings["DefaultConnectionString"].ConnectionString;
        }
        
        private void btnLoadData_Click(object sender, RoutedEventArgs e)
        {
            txtStoredProcedures.Text = string.Empty;
            tbMessage.Text = "Connecting.\n";
            DAL.ConnectionString = txtConnection.Text;
            string query = "select * from INFORMATION_SCHEMA.TABLES Where Table_Type = 'BASE TABLE';" +
                           "select *, Isnull((select 1 from INFORMATION_SCHEMA.KEY_COLUMN_USAGE keyCol WHERE OBJECTPROPERTY(OBJECT_ID(keyCol.constraint_name), 'IsPrimaryKey') = 1 AND keyCol.TABLE_NAME = col.TABLE_NAME AND keyCol.Column_NAME = col.Column_NAME), 0) IsPrimaryKey, COLUMNPROPERTY(object_id(col.TABLE_NAME), col.COLUMN_NAME, 'IsIdentity') IsIdentityKey from INFORMATION_SCHEMA.COLUMNS col; ";


            this.SchemaData = DAL.FillDataSet(query);

            tbMessage.Text += "Data Laoded.\n";
        }

        private void btnGenerateScript_Click(object sender, RoutedEventArgs e)
        {
            if (this.SchemaData != null)
            {
                DAL.ConnectionString = txtConnection.Text;

                tbMessage.Text += "Processing.\n";
                StoredProcedureEngine engine = new StoredProcedureEngine(this.txtPrefix.Text, this.txtAuthorName.Text);


                txtStoredProcedures.Text = engine.GetStoredProcedures(this.SchemaData.Tables[0], this.SchemaData.Tables[1]);

                tbMessage.Text += "Processed.\n";
            }
            else
            {
                tbMessage.Text += "Please Load Data.\n";
            }
        } 
    }
}
